// 2025/9/26
// 腐烂的苹果

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param grid int整型vector<vector<>> 
     * @return int整型
     */
    vector<pair<int, int>> dpos = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

    void dfs(vector<vector<int>>& time, vector<vector<int>>& grid, int i, int j, int count)
    {
        int m = time.size(), n = time[0].size();
        static auto isValid = [m, n](int x, int y){
            return (0 <= x && x < m && 0 <= y && y < n);
        };

        if(time[i][j] != -1 && time[i][j] < count)
            return;
        
        time[i][j] = count;
        for(auto &pr : dpos)
        {
            int x = i + pr.first, y = j + pr.second;
            if(isValid(x, y) && grid[x][y] == 1)
            {
                grid[x][y] = 2;
                dfs(time, grid, x, y, count + 1);
                grid[x][y] = 1;
            }
        }
    }

    int rotApple(vector<vector<int> >& grid) {
        // write code here
        int m = grid.size(), n = grid[0].size();
        vector<vector<int>> time(m, vector<int>(n, -1));
        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < n; j++)
            {
                if(grid[i][j] == 2)
                    dfs(time, grid, i, j, 0);
            }
        }
        int ans = 0;
        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < n; j++)
            {
                if(grid[i][j] == 1)
                {
                    if(time[i][j] == -1)
                        return -1;
                    ans = max(ans, time[i][j]);
                }
            }
        }
        return ans;
    }
};